import { queryConfigBykey, saveConfig } from "@/api/config";
import { uploadFile } from "@/api/file";
import { ABOUT_BG_KEY, INDEX_BG_KEY, LINK_BG_KEY, LOGIN_BG_KEY, NAVIGATION_BG_KEY, RESET_PWD_BG_KEY, UPDATE_PWD_BG_KEY, USER_INFO_BG_KEY, WHISPER_BG_KEY } from "@/constants/configKey.constant";
import { ConfigType } from "@/types/config";
import { message, UploadFile } from "antd";
import { useState, useCallback, useEffect } from "react";

export type FieldType = string[];
export const pageList = [
    {
      value: INDEX_BG_KEY,
      label: "首页",
    },
    {
      value: LINK_BG_KEY,
      label: "友情链接",
    },
    {
      value: WHISPER_BG_KEY,
      label: "私语",
    },

    {
      value: LOGIN_BG_KEY,
      label: "登录",
    },
    {
      value: USER_INFO_BG_KEY,
      label: "用户信息",
    },
    {
      value: UPDATE_PWD_BG_KEY,
      label: "修改密码",
    },
    {
      value: RESET_PWD_BG_KEY,
      label: "重置密码",
    },
    {
      value: NAVIGATION_BG_KEY,
      label: "导航",
    },
    {
      value: ABOUT_BG_KEY,
      label: "关于",
    },
  ]
export const useBgList = () => {
    const [messageApi] = message.useMessage();
    const [currentKey, setCurrentKey] = useState(INDEX_BG_KEY);
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [configInfo, setConfigInfo] = useState<ConfigType.Row<FieldType>>({
        id: "",
        title: "",
        configKey: "",
        config: [],
    });
    /**
     * 查询背景列表
     */

    const getFileListBykey = useCallback(async () => {
        if (!currentKey) return;
        const res = await queryConfigBykey(currentKey);
        if (res.code === 200) {
            const obj = res.data || {};
            const list = obj.config ? JSON.parse(obj.config) : [];
            setConfigInfo({
                id: obj.id,
                title: obj.title,
                configKey: obj.configKey,
                config: list,
            });
            const fileArr = list.map((item: string, i: number) => ({
                uid: new Date().getTime().toString() + i,
                name: String(i),
                status: "done",
                url: item,
            }));
            setFileList(fileArr);
        }
    }, [currentKey]);
    /**
     * 保存配置
     * @param config
     */
    const saveConfigInf = async (list:UploadFile[]) => {
        const config = list.map((item) => item.url);
        const params = {
            id: configInfo?.id,
            configKey: currentKey,
            config: JSON.stringify(config),
        };
        const res = await saveConfig(params);
        if (res.code === 200) {
            messageApi.success("保存成功");
            getFileListBykey();
        }
    };

    const uploadFileInf = async (file: any) => {
        const formData = new FormData();
        formData.append("file", file);
        try {
            const res = await uploadFile(formData);
            const list = [
                ...fileList,
                {
                    uid: new Date().getTime().toString(),
                    name: String(fileList.length + 1),
                    status: "done",
                    url: res.data,
                },
            ];
            saveConfigInf(list as UploadFile[]);
        } catch (error) {
            console.error(error);
        }
    };
    useEffect(() => {
        getFileListBykey();
    }, [getFileListBykey]);
    return {
        fileList,
        uploadFileInf,
        setFileList,
        currentKey,
        setCurrentKey,
        saveConfigInf
    }
}